<?php

namespace app\common\model;

use app\common\model\User;
use think\Db;
use think\Model;
use app\common\model\Ground as GroundModel;
use app\common\model\Device as DeviceModel;
use app\common\model\GroundChild;

class DeviceOrder extends Model
{


    // 表名
    protected $name = 'device_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'yd_time_text',
        'paytime_text',
        'status_text',
        'device_status_text'
    ];


    public function getTypeList()
    {
        return ['rs' => __('Type rs'), 'js' => __('Type js'), 'qs' => __('Type qs')];
    }

    public function getStatusList()
    {
        return ['created' => __('Status created'), 'paid' => __('Status paid'), 'expired' => __('Status expired')];
    }

    public function getDeviceStatusList()
    {
        return ['1' => __('Device_status 1'), '0' => __('Device_status 0')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getYdTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['yd_time']) ? $data['yd_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDeviceStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['device_status']) ? $data['device_status'] : '');
        $list = $this->getDeviceStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setYdTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 订单结算
     * @param int $orderid 订单号
     * @param float $payamount 支付金额
     * @param string $memo 备注
     * @return bool
     */
    public static function settle($orderid, $payamount, $memo = '')
    {
        $order = DeviceOrder::getByOrderid($orderid);
        if (!$order) {
            return false;
        }
//        if ($payamount != $order['amount']) {
//            \think\Log::write("[recharge][pay][{$orderid}][订单支付金额不一致]");
//            return false;
//        }
        if ($order['status'] != 'paid') {
            $order->payamount = $payamount;
            $order->paytime = time();
            $order->status = 'paid';
            $order->memo = $memo;
            $order->save();
            /*$u = Db::table('fa_user')->find($order['user_id']);
            if(!empty($u['openid'])){
                sendGoods($orderid,$u['openid']);
            }*/
            //发放分润start
            //获取设备属于哪个用户
            $device_user = Device::get($order['device_id']);
            //启动机器
            $socket_api = new \app\common\library\Socket();
            $socket_api->startDev([['device_name' => $device_user->name, 'time' => $order->yd_time * 60]]);
            if ($order->is_gifts == 0 && $order->is_free == 0) {
                //获取分润信息
                $commission = User::calculateCommission($order['amount'], $device_user->user_id);
                if ($commission) {
                    //查询此设备属于哪个代理
                    $agent_id = GroundModel::get($order['ground_id'])->user_id;
                    foreach ($commission as $v) {
                        if ($v['agent_id'] == $agent_id) {
                            //获取下级所有代理
                            $child = GroundChild::where('ground_id', $order['ground_id'])->select();
                            $agent_commission = $v['commission'];
                            $sy = $agent_commission;
                            foreach ($child as $v) {
                                $this_commission = $agent_commission * ($v['divide_rate'] / 100);
                                if ($this_commission > 0) {
                                    User::money($this_commission, $v['user_id'], '设备佣金结算', $order['ground_id'], $order['device_id'], $order['id']);
                                }
                                $sy -= $this_commission;//当前代理剩余佣金
                            }
                            if ($sy > 0) {
                                User::money($sy, $agent_id, '设备佣金结算', $order['ground_id'], $order['device_id'], $order['id']);
                            }
                        } else {
                            if ($v['commission'] > 0) {
                                User::money($v['commission'], $v['agent_id'], '设备佣金结算', $order['ground_id'], $order['device_id'], $order['id']);
                            }

                        }

                    }
                }
            }


        }
        return true;
    }

    public function ground()
    {
        return $this->belongsTo('Ground', 'ground_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function device()
    {
        return $this->belongsTo('Device', 'device_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
